import functools
import logging
from django.contrib.auth import login
from apps.users.models import User
from tenfold_pro import settings
from django.http import JsonResponse
from utils.token_jwt import check_token

def loginrequired(func):
    @functools.wraps(func)  # 修饰内层函数，防止当前装饰器去修改被装饰函数的属性
    def wrapper(self,request,*args,**kwargs):
        try:
            # 获取token值
            token = check_token(request.META.get('HTTP_AUTHORIZATION').split(' ')[1])
            # 查询登陆用户的数据
            user = User.objects.filter(id=token.get('user_id')).first()
        except Exception as e:
            logger = logging.getLogger('django')
            logger.info(e)
            return JsonResponse({'code': 400})
        # 把登录用户的数据保存在全局变量里面
        login(request,user)
        return func(self, request, *args, **kwargs)
    return wrapper